package c3g;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import java.io.*;
import java.util.ArrayList;

public class Filed {
    //读取java文件
    public ArrayList<String> readfile(String file, long numread) throws IOException {
        ArrayList<String> list =new  ArrayList();
        long count =0;
        RandomAccessFile rf =new RandomAccessFile(file,"r");
        long length =rf.length();
        if(length == 0){
            return list;
        }
        else {
            long pos =length -1;
            while (pos>0){
                pos--;
                rf.seek(pos);
                if( rf.readByte() == '\n' ){
                    String line =rf.readLine();
                    list.add(line);
                    count++;
                    if(count == numread){
                        break;
                    }
                }
            }
            if(pos ==0){
                rf.seek(0);
                list.add(rf.readLine());
            }
        }
        return list;
    }
    //通过模板生成文件
    public void makeFile(String fileVm, String out, Descriptorfile descriptorfile, Port port,String arge) throws IOException {

        VelocityEngine ve =new VelocityEngine();
        VelocityContext velocityContext =new VelocityContext();  //生成对象
        ve.init();
        Template template =ve.getTemplate(fileVm);   //设置模板文件
        velocityContext.put("list",port.getlist());            //设置容器
        velocityContext.put("useh",descriptorfile);
        velocityContext.put("port",port);
        StringWriter stringWriter =new StringWriter();
        template.merge(velocityContext,stringWriter);
        String r =stringWriter.toString();
        //生成不同的文件文件名不同
        String name = "";
        if(arge.equals("cs")) {
            StringBuilder sb =new StringBuilder();
            sb.append(out, 0, out.indexOf("make_")+6).append(port.getMajor(), 2, 4).append(port.getMinor(),2,4).append(out.substring(out.indexOf("make_")+6));
            name =sb.toString();
        }
        else {
            name =out;
        }
        //生成文件
        File file3 = new File(name);
        FileWriter fileWriter = new FileWriter(file3);
        fileWriter.append(r);                       //写入文件
        fileWriter.flush();
        fileWriter.close();
    }
    public void deleteFile(String filepath){
        File file =new File(filepath);
        if (file.exists()){
            File [] files=file.listFiles();
            for(File file1:files){
                file1.delete();
            }
        }
    }
}
